package com.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.constant.ProductConstant;
import com.common.to.SkuEsModel;
import com.common.to.SkuHasStockVo;
import com.common.to.SkuReductionTo;
import com.common.to.SpuBoundTo;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.common.utils.R;
import com.gulimall.product.dao.SpuInfoDao;
import com.gulimall.product.entity.*;
import com.gulimall.product.feign.CouponFeignService;
import com.gulimall.product.feign.SearchFeignService;
import com.gulimall.product.feign.WareFeignService;
import com.gulimall.product.service.*;
import com.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrService attrService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuvo(SpuSaveVo spuInfo) {
//        保存商品的基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());

        this.saveBaseSpuInfo(spuInfoEntity);

//        保存spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        List<String> decript = spuInfo.getDecript();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        this.saveBaseSpuInfoDesc(spuInfoDescEntity);


//        保存spu的图片集合
        List<String> images = spuInfo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);


//        保存spu的规格参数
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        productAttrValueService.saveBaseAttrs(baseAttrs,spuInfoEntity.getId());


//        保存spu的积分信息
        Bounds bounds = spuInfo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if(r.getCode()!=0){
            log.error("远程保存积分信息失败！");
        }


//        保存spu对应的所有sku信息
        List<Skus> skus = spuInfo.getSkus();
        if(skus!=null&&skus.size()>0) {
            skus.forEach(item -> {
                String defaultImg="";
                for (Images image : item.getImages()) {
                    if(image.getDefaultImg()==1){
                        defaultImg=image.getImgUrl();
                    }
                }



                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);

                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSaleCount(0L);

                skuInfoService.saveSkuInfo(skuInfoEntity);


                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(images1 -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setImgUrl(images1.getImgUrl());
                    skuImagesEntity.setDefaultImg(images1.getDefaultImg());
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());

                    return skuImagesEntity;
                }).filter(e->{
                    return !StringUtils.isEmpty(e.getImgUrl());
                }).collect(Collectors.toList());

                skuImagesService.saveBatch(skuImagesEntities);



//                SKU的销售属性
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> collect = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());

                    return skuSaleAttrValueEntity;

                }).collect(Collectors.toList());

                skuSaleAttrValueService.saveBatch(collect);

//                sku的优惠、满减信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if(skuReductionTo.getFullCount()>0||skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO)==1) {
                    R r1 = couponFeignService.saveSpuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void saveBaseSpuInfoDesc(SpuInfoDescEntity spuInfoDescEntity) {
        spuInfoDescService.save(spuInfoDescEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(w->{
                w.like("spu_name",key).or().eq("id",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
                wrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
                wrapper.eq("brand_id",brandId);
        }
        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
               wrapper.eq("publish_status",status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);


    }

    @Override
    public void up(Long spuId) {


        //把属于该spu的每一个sku都封装一下，然后上传
        //获取该spu的信息
        SpuInfoEntity spuInfoEntity = baseMapper.selectById(spuId);
        Long brandId = spuInfoEntity.getBrandId();
        Long catelogId = spuInfoEntity.getCatalogId();
        BrandEntity brandEntity = brandService.getById(brandId);
        String brandName = brandEntity.getName();
        String brandImg = brandEntity.getLogo();
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        String catelogName = categoryEntity.getName();


        //查询所有可以用来检索的规格属性
        //获取当前spu的所有规格属性
        //排除掉不能检索的规格属性
        List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.baseAttrListForspu(spuId);
        List<SkuEsModel.Attr> attrs = attrValueEntities.stream().filter(attr -> {
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            return attrEntity.getSearchType() == 1;
        }).map(entity -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            attr.setAttrId(entity.getAttrId());
            attr.setAttrName(entity.getAttrName());
            attr.setAttrValue(entity.getAttrValue());
            return attr;
        }).collect(Collectors.toList());

        //获取属于该spu的sku list
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
        //TODO: 发送远程调用，查看库存剩余

        List<Long> ids = skuInfoEntities.stream().map(skuInfoEntity -> {
            return skuInfoEntity.getSkuId();
        }).collect(Collectors.toList());
        Map<Long, Boolean> HasStockMap = null;
        try {
            wareFeignService.getSkuHasStock(ids);
            List<SkuHasStockVo> skuHasStock = wareFeignService.getSkuHasStock(ids);
            HasStockMap = skuHasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::isHasstock));
        }catch (Exception e){
            log.error("库存服务异常：原因：{}",e);
        }

        Map<Long, Boolean> finalHasStockMap = HasStockMap;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().filter(item->{
            return finalHasStockMap.get(item.getSkuId())!=null;
        }).map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setHasStock(finalHasStockMap.get(sku.getSkuId()));
            skuEsModel.setCatelogId(catelogId);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            skuEsModel.setBrandName(brandName);
            skuEsModel.setBrandImg(brandImg);
            skuEsModel.setCatelogName(catelogName);


            skuEsModel.setHotScore((long) 0);
            skuEsModel.setAttrs(attrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        R r = searchFeignService.productStatusUp(skuEsModels);
        //上架成功，修改上架状态
        if(r.getCode()==0){
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //TODO 重复调用的问题 重试机制？
        }

    }
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);

        return spuInfoEntity;
    }

}